package com.quanyue.haircut.shop.service.impl;

import com.quanyue.auto.util.AssertUtils;
import com.quanyue.haircut.domain.entity.Shop;
import com.quanyue.haircut.shop.mapper.ShopMapper;
import com.quanyue.haircut.shop.service.ShopService;
import com.quanyue.haircut.user.mapper.HaircutMerchantMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShopServiceImpl implements ShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private HaircutMerchantMapper haircutMerchantMapper;

    @Override
    public Shop createShop(Shop shop, Integer merchantNo) {
        // 判断当前商户是否已达到上限
        Integer child = haircutMerchantMapper.findByMerchantNo(merchantNo).getChildQuantity();
        Integer childNow = shopMapper.findByMerchantNoValid(merchantNo).size();
        if (childNow >= child) throw new AssertUtils.ValidateException("店铺数量已达到上线:" + child);
        shop.setMerchantNo(merchantNo);
        shop.setCreateTime(LocalDateTime.now());
        shop.setModifyTime(LocalDateTime.now());
        shop.setDelFlag(false);
        shopMapper.insert(shop);
        return shop;
    }

    @Override
    public void updateShop(Shop shop) {
        Shop check = shopMapper.findOne(shop.getId());
        AssertUtils.notNull(check, "店铺信息校检出错");
        shop.setCreateTime(check.getCreateTime());
        shop.setModifyTime(LocalDateTime.now());
        shop.setDelFlag(false);
        shopMapper.updateSelective(shop);
    }

    @Override
    public void deleteShop(Integer id) {
        Shop check = shopMapper.findOne(id);
        AssertUtils.notNull(check, "店铺信息校检出错");
        shopMapper.deleteOne(id);
    }

    @Override
    public List <Shop> findShop(Integer merchantNo) {
        return shopMapper.findByMerchantNoValid(merchantNo);
    }
}
